/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gioo.android;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import com.google.android.gcm.GCMBaseIntentService;

public final class GCMIntentService extends GCMBaseIntentService
{
	
	public static final String ACTION_MESSAGE = "com.gioo.android.movieonsactivity.message";
	
	 
	
     String TAG = "GCMIntentService ";  
     static final String SENDER_ID = "59375700515";
      String c2dm_msg = null;
      public GCMIntentService() 
    {
     super(SENDER_ID);
      Log.d("GCM", "GCMIntentService created.");
     }
      
 
    @Override
     protected void onRegistered(Context context, String registrationId) 
    {
        Log.d("GCM", "Device registered: regId = " + registrationId);
       //GCMAppServer.post(context, registrationId);  
        
        MovieonsActivity.registrationId = registrationId;
        
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.twitaddons.com/app/save_client_gcm_token.php");
        
        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("acc", MovieonsActivity.googleAccounts));
            nameValuePairs.add(new BasicNameValuePair("pn", MovieonsActivity.phoneNumber));
            nameValuePairs.add(new BasicNameValuePair("dt", registrationId));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response;
            response = httpclient.execute(httppost);
            
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }
 
     @Override
     protected void onUnregistered(Context context, String registrationId) 
    {
        Log.d("GCM", "unregistered = "+ registrationId);
        //GCMAppServer.delete(context, registrationId);
     }
 
     @Override
      protected void onError(Context arg0, String errorId) 
     {
         Log.d("GCM", "onError error: " + errorId);
     } 
 
     @Override
     protected boolean onRecoverableError(Context context, String errorId) 
    {
        Log.d("GCM", "onRecoverableError error: " + errorId);
        return super.onRecoverableError(context, errorId);
     }
 
 
	 @Override
	 protected void onMessage(Context context, Intent intent) 
	 {
	      Log.d("GCM", "onMessage received");
	       if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) 
	     {
	      c2dm_msg = intent.getStringExtra("msg"); ///intent.getExtras().getString("msg");
	      GET_GCM();
	      Log.d("GCM", c2dm_msg);
	     }
	 }
	 
	 
	 
	 
	 /*
	 protected void onReceive(Context context, Intent intent){
		 
		 
		 
		  //TODO Auto-generated method stub
	        Log.d("ImmortalService", "RestartService called!@!@@@@@#$@$@#$@#$@#");
	       
	        if(intent.getAction().equals(ACTION_RESTART_PERSISTENTSERVICE)) {
	               Intent i = new Intent(context, PersistentService.class);
	//Intent i = new Intent(this, PersistentService.class);
	                context.startService(i);
	        }    
	 }
	 */


	
 
	 public void GET_GCM() 
	 { 
	     Thread thread = new Thread(new Runnable() 
	     { 
	    	 @Override
	         public void run() 
	         { 
	    		 Log.d("wake", "starting wake");
	    		 wakeUpHandler.sendEmptyMessage(0);
	    		 toastUphandler.sendEmptyMessage(0); 
	    		
	          
	         } 
	     }); 
	     thread.start(); 
	 } 
	 
	 
	 Handler wakeUpHandler = new Handler(){
			public void handleMessage(Message msg) {
				SplashActivity.splashActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
			            | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
			            | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
			            | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
				Log.d("wake", "onrelease wake");
				AlarmWakeLock.wakeLock(SplashActivity.splashActivity);
				AlarmWakeLock.releaseWakeLock();
			};
		};
		
 
	 private static int count = 0;
	 private Handler toastUphandler = new Handler() 
	 {
	     public  void handleMessage(Message msg) 
	     { 
	    	
	    	 
	    	 
	         // 새 토스트 발생시킴.
	         Context context = getApplicationContext();
	         int duration = Toast.LENGTH_LONG;
	         Toast toast = Toast.makeText(context, c2dm_msg, duration);
	         toast.show(); 
	         
	         
	         // Execute MovieonsActivity 
	         /*
	         Intent intent = new Intent(context, MovieonsActivity.class);
	         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
	         context.startActivity(intent); 
	    	 */
	         
	         String strMsg = c2dm_msg;
	         
	         
	         
	         NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		        Notification note = new Notification(R.drawable.icon, "무비온즈 새소식", System.currentTimeMillis());
		        Intent notificationIntent = new Intent(context, MovieonsActivity.class);
		        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
		        PendingIntent pendingIntent = PendingIntent.getActivity(MovieonsActivity.mainActivity, 0, notificationIntent, 0);
		        note.setLatestEventInfo(context, "무비온즈 새소식", strMsg, pendingIntent);
		        note.number = count++;
		        note.defaults |= Notification.DEFAULT_SOUND;
				note.defaults |= Notification.DEFAULT_VIBRATE;
				note.defaults |= Notification.DEFAULT_LIGHTS;
				note.flags |= Notification.FLAG_AUTO_CANCEL;
		        notificationManager.notify(0, note);
	    	 
		        
		        
	         /*
	    	//testing for dialog
	       	 AlertDialog.Builder dialog = new AlertDialog.Builder(getApplicationContext());
	       	 dialog.setMessage("New message : "+ "ggg" );
	       	 dialog.setNeutralButton("View", new OnClickListener()       
	      	 {
	      	     @Override
	      	     public void onClick(DialogInterface dialog, int which)
	      	     {
	      	    	 
	      	     }
	      	 });
	       	 dialog.show();
	       	 
	    	 */
	    	 
	    	 
	         c2dm_msg = null;
	     } 
	 };
}
